package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public abstract class SQLUtil {

  private static final String dbUrl = "jdbc:mysql://localhost/progin_171_13509096";
  private static final String dbClass = "com.mysql.jdbc.Driver";
  private static final String username = "progin";
  private static final String password = "progin";
  
  public static String[] Query(String query) {
    try {
      Class.forName(dbClass);
      Connection con = DriverManager.getConnection(dbUrl, username, password);
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);
    
      ArrayList<String> ret = new ArrayList<String>();
      while (rs.next()) {
        ret.add(rs.getString(1));
      }
    
      con.close();
      
      return Util.toArray(ret);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    
    // Fail
    return null;
  }
  
  public static byte[] GetBytes(String id) {
    try {
      Class.forName(dbClass);
      Connection con = DriverManager.getConnection(dbUrl, username, password);
      Statement stmt = con.createStatement();
      ResultSet result = stmt.executeQuery(
          "SELECT data FROM files WHERE id_file='" + id + "'");
      while (result.next()) {
        // Get data from the binary column
        return result.getBytes(1);
      }
      Util.Warning("No data found for id=" + id);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }
  
  public static void Modify(String query) {
    System.out.println("Query received:" + query);
    String dbUrl = "jdbc:mysql://localhost/progin_171_13509096";
    String dbClass = "com.mysql.jdbc.Driver";
    String username = "progin";
    String password = "progin";
    
    try {
      Class.forName(dbClass);
      Connection con = DriverManager.getConnection(dbUrl, username, password);
      Statement stmt = con.createStatement();
      stmt.execute(query);
      con.close();
      return;
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    // Fail
    return;
  }
}
